import { ApiRequest } from '@/service'
import md5 from 'md5'
import moment from 'moment'

const mixinKeyEncTab = [
  46, 47, 18, 2, 53, 8, 23, 32, 15, 50, 10, 31, 58, 3, 45, 35, 27, 43, 5, 49,
  33, 9, 42, 19, 29, 28, 14, 39, 12, 38, 41, 13, 37, 48, 7, 16, 24, 55, 40,
  61, 26, 17, 0, 1, 60, 51, 30, 4, 22, 25, 54, 21, 56, 59, 6, 63, 57, 62, 11,
  36, 20, 34, 44, 52
]

// 对 imgKey 和 subKey 进行字符顺序打乱编码
const getMixinKey = (orig: string) => mixinKeyEncTab.map(n => orig[n]).join('').slice(0, 32)

// 为请求参数进行 wbi 签名
const encWbi = (params: { [key: string]: any }, img_key: string, sub_key: string) => {
  console.log(params)
  const mixin_key = getMixinKey(img_key + sub_key)
  const curr_time = Math.round(Date.now() / 1000)
  const chr_filter = /[!'()*]/g

  Object.assign(params, { wts: curr_time }) // 添加 wts 字段
  // 按照 key 重排参数
  const query = Object
    .keys(params)
    .sort()
    .map(key => {
      // 过滤 value 中的 "!'()*" 字符
      const value = params[key].toString().replace(chr_filter, '')
      return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
    })
    .join('&')

  const wbi_sign = md5(query + mixin_key) // 计算 w_rid

  return {
    w_rid: wbi_sign,
    wts: curr_time
  }
}

const getNavKeys = async () => {
  let currentDate = moment().format('YYYYMMDD')
  let nav_keys: BiliNavKeysType = {
    img_url: 'aaaaaaaa',
    sub_url: 'aaaaaaaa',
    currentDate
  }
  let needRequest = false
  let historyNavKeys = localStorage.getItem('nav_keys')
  if (!historyNavKeys) {
    needRequest = true
  } else {
    nav_keys = JSON.parse(historyNavKeys)
    if (nav_keys.currentDate !== currentDate) {
      needRequest = true
    }
  }
  if (needRequest) {
    const res: any = await ApiRequest({
      api: {
        url: '/blapi/x/web-interface/nav',
        method: 'GET',
        description: '获取wbikeys',
        useElseProxy: true
      },
      headers: {
        // SESSDATA 字段
        // 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
        // "Set-Cookie": encodeURIComponent("buvid3=831FE83E-ADEA-41DD-BCDD-5159F9CB903698213infoc; b_nut=1736668698; enable_web_push=DISABLE; home_feed_column=4; browser_resolution=1380-993; buvid4=D71A9300-5657-8148-7A79-CF977883CCA799378-025011207-71HgfdojuyvBUF1DKdVR0A%3D%3D; bili_ticket=eyJhbGciOiJIUzI1NiIsImtpZCI6InMwMyIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MzcwMDcxOTEsImlhdCI6MTczNjc0NzkzMSwicGx0IjotMX0.PcihJRJ8ZiMQva-NXTKxFOdvpLPEG-My642ASHSbGH0; bili_ticket_expires=1737007131; header_theme_version=CLOSE; CURRENT_FNVAL=2000; rpdid=|(u)~JY)~lm~0J'u~JYYY))YR; SESSDATA=ba41e4ae%2C1752287404%2C704df%2A12CjB3v7B55FXNg4aRKcN3FvPNrI3J8NMKask_VH0H6QrmP81pYRo9SrgtzYAsYekD6GsSVjJxbk5TUnBCZXM5eDRvSkZJazJIVERGOXJrbWZtN3VOeFlFOU5sR2tJLXBfeXFfOFJQOThrVmZLZjdTUkJxUnBkbXdwcGZSSTVJQndPd0ROTzBRUDJBIIEC; bili_jct=a64347d12d585801f65bbd7c62b9396f; DedeUserID=8220922; DedeUserID__ckMd5=ed249f85ec73ddce; sid=4takg31i; bp_t_offset_8220922=1022230704966074368; bsource=search_bing"),
        Referer: 'https://www.bilibili.com/', // 对于直接浏览器调用可能不适用
        Cookie: 'SESSDATA=292e4fcb%2C1754019232%2Cb579e%2A21CjAU9DqyIMushuWEVYIjXfSk3JWBA_3e7ADBZHNecwShk1-lG0-T3PDEYHTOGvsaY_wSVlljUzZoZVNkTU0ybXRQeElEVkV3aGpERFhjOEtILXJEakhwT0dObURzb1FZY1hfZzRYX0pyanRTZ0sySUV4anpldWNDTzFLdHd6X05pQndRNEdsS0V3IIEC'
      }
    })
    let new_nav_keys = res.data.wbi_img
    if (!new_nav_keys.img_url || !new_nav_keys.sub_url) {
      alert('img_url/sub_url 获取失败请检查')
    } else {
      localStorage.setItem('nav_keys', JSON.stringify({ ...new_nav_keys, currentDate }))
    }
  } else {
    nav_keys = JSON.parse(historyNavKeys || '{}')
  }
  const { img_url = 'get_img_url_fail', sub_url = 'get_sub_url_failed' } = nav_keys
  console.log(img_url, sub_url)
  return {
    img_key: img_url.slice(
      img_url.lastIndexOf('/') + 1,
      img_url.lastIndexOf('.')
    ),
    sub_key: sub_url.slice(
      sub_url.lastIndexOf('/') + 1,
      sub_url.lastIndexOf('.')
    )
  }
}

const GetWBIParams = async (params: any) => {
  const web_keys = await getNavKeys()
  const { img_key, sub_key } = web_keys
  const WBI = encWbi(params, img_key, sub_key)
  return {
    ...params,
    ...WBI
  }
}

export default GetWBIParams
